<script setup lang="ts">
import router from '@/router'
import { getMobileCode, loginByMobile, loginByPassword } from '@/services/user'
import { useUserStore } from '@/stores'
import type { User } from '@/types/user'
import { codeRules, mobileRules, passwordRules } from '@/utils/rules'
import { showSuccessToast, showToast, type FormInstance } from 'vant'

import { onUnmounted, ref } from 'vue'

const mobile = ref('13230000027')
const password = ref('abc12345')
const code = ref('')
const agree = ref(false)
// 是密码登录还是验证码登录
const isPass = ref(true)

// 补充说明：只要能够进入 login 函数，那么表单校验一定是通过了
const login = async () => {
  if (!agree.value) return showToast('请勾选我已同意')
  // #region 发请求
  // useUserStore().saveUser(await loginByPassword(mobile.value, password.value))
  let user: User | null = null

  if (isPass.value) {
    user = await loginByPassword(mobile.value, password.value)
  } else {
    user = await loginByMobile(mobile.value, code.value)
  }

  // const user = isPass.value
  //   ? await loginByPassword(mobile.value, password.value)
  //   : await loginByMobile(mobile.value, code.value)

  const userStore = useUserStore()
  userStore.saveUser(user)
  // #endregion

  showSuccessToast('登录成功')

  // #region 登录成功跳转逻辑
  const { returnUrl } = router.currentRoute.value.query
  // 判断是否有回跳地址
  // if (returnUrl) {
  //   // 说明有回跳地址
  //   router.push(returnUrl as string)
  // } else {
  //   // 跳个人中心
  //   router.push({ name: 'UserIndex' })
  // }
  router.push((returnUrl as string) || { name: 'UserIndex' })
  // #endregion
}

const refForm = ref<FormInstance | null>(null)

// 倒计时
const time = ref(0)

// 定时器id
let timerId = -1

// 发送验证码
const send = async () => {
  // 如果目前已经在倒计时中，就直接 return
  if (time.value > 0) return

  // 先验证手机号码有没有输入正确
  await refForm.value?.validate('mobile')

  // 如果能走到这里，说明验证通过
  // 发请求
  code.value = await getMobileCode(mobile.value, 'login')

  // 倒计时效果什么时候开启，请求发送成功
  showSuccessToast('发送成功')
  time.value = 60
  timerId = setInterval(() => {
    time.value--
    if (time.value === 0) {
      clearInterval(timerId)
    }
  }, 1000)
}

onUnmounted(() => {
  // 页面卸载的同时清除定时器
  clearInterval(timerId)
})

// 是否显示密码
const showPassword = ref(false)
</script>

<template>
  <div class="login-page">
    <cp-nav-bar
      right-text="注册"
      @click-right="$router.push({ name: 'RegisterIndex' })"
    ></cp-nav-bar>
    <!-- 头部 -->
    <div class="login-head">
      <h3>{{ isPass ? '密码登录' : '短信验证码登录' }}</h3>
      <a href="javascript:;" @click="isPass = !isPass">
        <span>{{ isPass ? '短信验证码登录' : '密码登录' }}</span>
        <van-icon name="arrow"></van-icon>
      </a>
    </div>
    <!-- 表单 -->
    <!-- submit 触发时机：所有的表单单项都校验通过后，才会触发submit事件，执行到login函数 -->
    <van-form ref="refForm" autocomplete="off" @submit="login">
      <van-field
        v-model="mobile"
        name="mobile"
        :rules="mobileRules"
        placeholder="请输入手机号"
        type="tel"
      ></van-field>
      <van-field
        v-if="isPass"
        v-model="password"
        :rules="passwordRules"
        placeholder="请输入密码"
        :type="showPassword ? 'text' : 'password'"
      >
        <template #button>
          <cp-icon
            @click="showPassword = !showPassword"
            :name="`login-eye-${showPassword ? 'on' : 'off'}`"
          ></cp-icon>
        </template>
      </van-field>
      <van-field
        v-else
        v-model="code"
        :rules="codeRules"
        placeholder="短信验证码"
      >
        <template #button>
          <span class="btn-send" :class="{ active: time > 0 }" @click="send">
            {{ time > 0 ? `${time}s后再次发送` : '发送验证码' }}
          </span>
        </template>
      </van-field>
      <div class="cp-cell">
        <van-checkbox v-model="agree">
          <span>我已同意</span>
          <a href="javascript:;">用户协议</a>
          <span>及</span>
          <a href="javascript:;">隐私条款</a>
        </van-checkbox>
      </div>
      <div class="cp-cell">
        <!-- native-type 表明按钮原生类型，必须加上后才能触发所在表单的 submit 事件 -->
        <van-button block type="primary" native-type="submit">登 录</van-button>
      </div>
      <div class="cp-cell">
        <a href="javascript:;">忘记密码？</a>
      </div>
    </van-form>
    <!-- 底部 -->
    <div class="login-other">
      <van-divider>第三方登录</van-divider>
      <div class="icon">
        <img src="@/assets/qq.svg" alt="" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.login {
  &-page {
    padding-top: 46px;
  }
  &-head {
    display: flex;
    padding: 30px 30px 50px;
    justify-content: space-between;
    align-items: flex-end;
    line-height: 1;
    h3 {
      font-weight: normal;
      font-size: 24px;
    }
    a {
      font-size: 15px;
    }
  }
  &-other {
    margin-top: 60px;
    padding: 0 30px;
    .icon {
      display: flex;
      justify-content: center;
      img {
        width: 36px;
        height: 36px;
        padding: 4px;
      }
    }
  }
}
.van-form {
  padding: 0 14px;
  .cp-cell {
    height: 52px;
    line-height: 24px;
    padding: 14px 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    .van-checkbox {
      a {
        color: var(--cp-primary);
        padding: 0 5px;
      }
    }
  }
  .btn-send {
    color: var(--cp-primary);
    &.active {
      color: rgba(22, 194, 163, 0.5);
    }
  }
}
</style>
